package app.fugema.shop.main.order.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.lifecycle.Observer;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityOrderDetailBinding;
import app.fugema.shop.main.order.adapter.OrderDetailAdapter;
import app.fugema.shop.main.order.adapter.OrderFunButtonAdapter;
import app.fugema.shop.main.order.model.OrderExpressResult;
import app.fugema.shop.main.order.model.OrderAddressHeadBean;
import app.fugema.shop.main.order.model.OrderDetailResult;
import app.fugema.shop.main.order.model.OrderFunBtn;
import app.fugema.shop.main.order.model.OrderPayFootBean;
import app.fugema.shop.main.order.model.TheOrder;
import app.fugema.shop.main.order.vm.OrderListVM;

import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DateUtils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.RxTimer;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.connector.BaseItemTypeInterface;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;

import java.util.List;

public class OrderDetailActivity extends BaseTitleActivity<ActivityOrderDetailBinding, OrderListVM>
{


    public static void start(Context context, long orderId)
    {
        Intent starter = new Intent(context, OrderDetailActivity.class);
        starter.putExtra("orderNumber", orderId);
        context.startActivity(starter);
    }

    private OrderDetailAdapter orderDetailAdapter;
    //底部按钮
    private OrderFunButtonAdapter adapterButton;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
    }

    private long orderId;

    private String userKey;

    private OrderDetailResult detailResult;

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("订单详情",R.color.white);

        orderDetailAdapter = new OrderDetailAdapter(this, viewModel);
        binding.rvRecyclerView.setAdapter(orderDetailAdapter);
        adapterButton = new OrderFunButtonAdapter(this, viewModel);
        binding.rvRecyclerButton.setAdapter(adapterButton);

        userKey = LoginUtils.getToken();

        //测试 聊天
        /*
        binding.ivStatusImg.setOnClickListener(v -> {
            if( UIUtils.isNotEmpty( detailResult )  )
            {
                if( UIUtils.isNotEmpty( detailResult.getCustomerServices() ) && !detailResult.getCustomerServices().isEmpty() )
                {
                    CustomerServicesBean services = detailResult.getCustomerServices().get(0);
                    String urlBase = "https://fugema-kefu.top/index/index/home?";
                    StringBuffer sbf = new StringBuffer();
                    sbf.append(urlBase);
                    sbf.append("visiter_id=");
                    if( UIUtils.isNotEmpty( services.getId() ) )
                    {
                        sbf.append(services.getId());
                    }
                    sbf.append("&");
                    sbf.append("visiter_name=");
                    if( UIUtils.isNotEmpty( services.getUserName() ) )
                    {
                        sbf.append(services.getUserName());
                    }
                    sbf.append("&");
                    sbf.append("avatar=");
                    sbf.append("&");
                    sbf.append("business_id=");
                    if( UIUtils.isNotEmpty( services.getShopId() ) )
                    {
                        sbf.append(services.getShopId());
                    }
                    sbf.append("&");
                    sbf.append("groupid=0");
                    sbf.append("&");
                    sbf.append("product=");
                    if( UIUtils.isNotEmpty( services.getProductJson() ) )
                    {
                        sbf.append(services.getProductJson());
                    }
                    sbf.append("&");
                    sbf.append("user_name=");
                    if( UIUtils.isNotEmpty(PublicGlobal.getUserInfo().getNick()) )
                    {
                        sbf.append(PublicGlobal.getUserInfo().getNick());
                    }
                    sbf.append("&");
                    sbf.append("date=1");
                    https://fugema-kefu.top/index/index/home?visiter_id=&visiter_name=&avatar=&business_id=9&groupid=0&product={}&user_name=canxi&date=1
                    WebActivity.start(this ,sbf.toString());
                }
            }
        });
        */
    }


    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(AppConstants.EventKey.ORDER_RECEIPT, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String o) {
                initData(getIntent());
            }
        });
        LiveEventBus.get(AppConstants.EventKey.ORDER_AFTER_SALE, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String o) {
                initData(getIntent());
            }
        });

        LiveEventBus.get(AppConstants.EventKey.ORDER_CANCEL, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String o) {
                finish();
            }
        });

        LiveEventBus.get(AppConstants.EventKey.COMMENT_COMPLETE, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String o) {
                finish();
            }
        });
        LiveEventBus.get(BaseConstant.EventKey.PAY_SUCCESS, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String o) {
                initData(getIntent());//支付成功后刷新
            }
        });

        // 待收货  待评价 状态 跳转 退款退货
        LiveEventBus.get("refundOrder", Integer.class).observe(this, itemId -> {

            if( itemId != 0 )
            {
                OrderAfterSaleSelectActivity.start(OrderDetailActivity.this, String.valueOf(orderId ),String.valueOf(itemId));
            }
            });

    }

    @Override
    protected void initData(Intent intent)
    {
        super.initData(intent);
        orderId = intent.getLongExtra("orderNumber",0);
        if(orderId == 0 || UIUtils.isEmpty(userKey )) return;

        // 查询订单详情
        viewModel.getOrderDetail(orderId,userKey).observe(this, new BaseViewObserver<LiveDataWrapper<OrderDetailResult>>(getActivity())
        {
            @Override
            protected void onSuccess(LiveDataWrapper<OrderDetailResult> data)
            {
                detailResult = data.data;

                showOrderDetail( data.data );

                if( data.data.getOrder().getOrderStatus() == 3)
                {
                    queryExpressInfo();
                }

                //底部的按扭
                List<OrderFunBtn> btnInfos = OrderFunButtonAdapter.getDetailStatesButton( data.data.getOrder().getOrderStatus(),data.data.getOrder().isCanRefund());
                if (UIUtils.isNotEmpty(btnInfos))
                {
                    for (OrderFunBtn orderBtn : btnInfos)
                    {
                        orderBtn.setContent(""+data.data.getOrder().getId());
                        orderBtn.setTotalAmount( data.data.getOrder().getRealTotalAmount() );
                    }
                }
                adapterButton.setDataList(btnInfos);
            }
            @Override
            public boolean isEmptyData(LiveDataWrapper<OrderDetailResult> data)
            {
                return UIUtils.isEmpty(data.data.getOrder());
            }
        });
    }
    //显示页面
    private void showOrderDetail(OrderDetailResult orderResult)
    {
        TheOrder orderInfo = orderResult.getOrder();

        //PublicGlobal.getOrderState(orderInfo.getOrderStatus()) 订单状态转文字
        binding.tvOrderStatus.setText( orderInfo.getStatus() );
        // 设置订单状态提示语（没有）
        //binding.tvStatusTips.setVisibility(View.VISIBLE);
        //binding.tvStatusTips.setText("商家正在备货中，请耐心等候");

        switch (orderInfo.getOrderStatus())
        {
            case 1:
            case 2:
            case 3:
            case 4:
                binding.ivStatusImg.setImageResource(R.mipmap.ic_order_waiting);
                break;
            case 5:
                binding.ivStatusImg.setImageResource(R.mipmap.ic_order_complate);
                break;
            case 6:
                binding.ivStatusImg.setImageResource(R.mipmap.ic_order_refuse);
                break;
        }

        LogUtil.e("设置页面信息");
        //显示地址
        OrderAddressHeadBean headBean = OrderAddressHeadBean.getAddressByOrderInfo(orderInfo);
        headBean.setState(1);
        orderDetailAdapter.addHeaderView(headBean, 1);

        orderDetailAdapter.setDataList(orderResult.getOrderItem());

        OrderPayFootBean footerBean = OrderPayFootBean.getOrderFootByOrderInfo(orderInfo);
        footerBean.setItemType(BaseItemTypeInterface.TYPE_FOOT);
        orderDetailAdapter.addFooterView(footerBean);
        /*
        OrderDetailFooterBean orderDetailFooterBean = new OrderDetailFooterBean();
        orderDetailFooterBean.setItemType(BaseItemTypeInterface.TYPE_FOOT_ONE);
        orderDetailFooterBean.setOrderNumber(orderNumber);
        orderDetailAdapter.addFooterView(orderDetailFooterBean);
        */

        //待付款1  和 待收货  显示倒计时    OrderStatus 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败
        if (orderResult.getOrder().getOrderStatus() == 1 || orderResult.getOrder().getOrderStatus() == 3)
        {
           startRxTimer(orderResult.getOrder().getOrderDate(), orderResult.getOrder().getOrderStatus());
        }
        //待发货
        else if (orderResult.getOrder().getOrderStatus() == 2)
        {
           binding.tvDateTime.setVisibility(View.VISIBLE);
           binding.tvDateTime.setText("等待发货中，请您耐心等待");
        }
    }

    private void queryExpressInfo()
    {
        //查物流
        viewModel.checkOrderExpressInfo(orderId ,userKey)
                .observe(this, new BaseViewObserver<LiveDataWrapper<OrderExpressResult>>() {
                    @Override
                    protected void onSuccess(LiveDataWrapper<OrderExpressResult> data)
                    {
                        /*
                        IntegralBean checkBean = data.data.getData().getData().get(0);
                        checkBean.setItemType(BaseItemMultiType.TYPE_HEAD_ONE);
                        checkBean.setStateContext(orderNumber);
                        orderDetailAdapter.addHeaderView(Object, 0);
                        orderDetailAdapter.notifyDataSetChanged();
                        */
                    }

                    @Override
                    public boolean isEmptyData(LiveDataWrapper<OrderExpressResult> data)
                    {
                        return UIUtils.isEmpty(data.data.getComment());
                    }
                });
    }

    /**
     * 根据订单状态显示倒计时
     * @param createTime
     * @param status
     */
    private void startRxTimer(String createTime, int status)
    {
        binding.tvDateTime.setVisibility(View.VISIBLE);
        changeTimeText(createTime, status);
        if (status == 1)
        {
            RxTimer rxTimer = new RxTimer();
            rxTimer.interval(1000, new RxTimer.RxAction() {
                @Override
                public void action(long number) {
                    changeTimeText(createTime, status);
                }
            });
        }

    }

    private void changeTimeText(String createTime, int status)
    {
        //待付款
        if (status == 1) {
            long time = DateUtils.dateStringToLong(createTime) + 24*60 * 60 * 1000;//下单时间24小时后
            long spe = time - System.currentTimeMillis();
            if (spe > 0) {
                long m = spe / (1000);//多少秒
                long mText = m % 60;
                long hText = m / 60;
                LogUtil.d("剩" + hText + "分" + mText + "秒自动关闭");
                binding.tvDateTime.setText("剩" + hText + "小时" + mText + "分钟自动关闭");
            }

        }
        //待收货
        else if (status == 3)
        {
            long time = DateUtils.getDayLong(10, DateUtils.dateStringToLong(createTime));//下单时间10天后
            long spe = time - System.currentTimeMillis();
            if (spe > 0) {
                long m = spe / (60 * 60 * 1000);//多少小时
                long mText = m % 24;
                long hText = m / 24;
                binding.tvDateTime.setText("还剩" + hText + "天" + mText + "小时自动确认");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
